

import sys, os, django
 
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # 把manage.py所在目录添加到系统目录
os.environ['DJANGO_SETTINGS_MODULE'] = 'hg_survey.settings' # 设置setting文件
django.setup() # 初始化Django环境

import pandas as pd
from survey.models import Survey, Question
from django.contrib.auth.models import User
from hg_survey.logging import evt_logger


def delete_survey(survey_id):
    try:
        survey = Survey.objects.get(pk=survey_id)
    except Survey.DoesNotExist as e:
        return
    else:
        survey.delete()

def insert_survey(survey_id, survey_name):
    try:
        test_user = User.objects.get(username='test')
    except User.DoesNotExist:
        test_user = User(username='test', password="test1234", is_staff=True)
        test_user.save()

    survey = Survey(survey_id=survey_id,
                    survey_name=survey_name,
                    create_user=test_user,
                    update_user=test_user,)
    survey.save()
    
    return survey.survey_id

def insert_question(filepath, survey_id):
    if not filepath.endswith('xlsx'):
        raise ValueError('导入模板必须是xlsx格式')
    data = pd.read_excel(filepath)
    data.fillna('', inplace=True)
    data = data.melt(id_vars=list(data.columns[:5]), var_name='order', value_name='option')
    data = data.groupby(list(data.columns[:5])).option.apply(lambda x: " ".join(x).strip().split(' '))
    data = data.reset_index()

    qtype_map = {
        '单选': 'radio',
        '多选': 'checkbox',
        '填空': 'text'
    }

    survey = Survey.objects.get(pk=survey_id)

    counter = 1
    for _, series in data.iterrows():
        qid = survey_id + '-' + str(series['问题编号']) + "-" + str(counter)
        qnum = series['问题编号']
        qtype = qtype_map[series['问题类型']]
        qtext = series['题目']
        fill_others = True if series['其他选项是否填空'] == "是" else False
        required = True if series['是否必填'] == "是" else False

        options = []
        if qtype != 'text':
            for idx, op in enumerate(series['option']):
                opid = qid + "-" + str(idx)
                options.append({'id': opid, 'text': op})

        question = Question(
            qid=qid,
            qtext=qtext,
            qtype=qtype,
            qnum=qnum,
            required=required,
            fill_others=fill_others,
            survey=survey,
            options=options
        )
        question.save()

        counter += 1
        evt_logger.info(f'{counter}: {question} created')


if __name__ == "__main__":
    filename = "2018问卷题目导入模板.xlsx"
    delete_survey('test-2018-survey-01')
    survey_id = insert_survey('test-2018-survey-01', '2018新生调查问卷')
    insert_question(filename, survey_id)
